package com.grablist.feihu.grablist.ui.actviity.user;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.alertview.AlertView;
import com.jakewharton.rxbinding.view.RxView;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.Bind;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import com.grablist.feihu.grablist.R;
import com.grablist.feihu.grablist.base.BaseActivity;
import com.grablist.feihu.grablist.comm.MyApplication;
import com.grablist.feihu.grablist.event.NetErrorEvent;
import com.grablist.feihu.grablist.ui.actviity.user.biz.CertificationBiz;
import com.grablist.feihu.grablist.ui.actviity.user.component.DaggerCertificationComponent;
import com.grablist.feihu.grablist.ui.actviity.user.contract.CertificationContract;
import com.grablist.feihu.grablist.ui.actviity.user.module.CertificationModule;
import com.grablist.feihu.grablist.ui.actviity.user.presenter.CertificationPresenter;
import com.grablist.feihu.grablist.util.AlertUtils;
import com.grablist.feihu.grablist.util.LogUtils;
import com.grablist.feihu.grablist.util.StringUtils;
import rx.functions.Action1;

/**
 * Created by admin on 2017/12/2.
 */

public class CertificationAct extends BaseActivity implements CertificationContract.View {


    @Inject
    CertificationPresenter presenter;
    @Inject
    CertificationBiz biz;
    @Bind(R.id.certification_city)
    EditText city;
    @Bind(R.id.certification_company)
    EditText company;
    @Bind(R.id.certification_compangy_phone)
    EditText compangyPhone;
    @Bind(R.id.certification_user_name)
    EditText userName;
    @Bind(R.id.certification_user_number)
    EditText userNumber;
    @Bind(R.id.certification_user_card)
    ImageView userImage;
    @Bind(R.id.certification_company_card)
    ImageView companyImage;
    @Bind(R.id.certification_submit)
    TextView submit;
    @Bind(R.id.certification_info)
    TextView certificationInfo;
    @Bind(R.id.shen_fen_shi)
    ImageView shenFenShi;
    @Bind(R.id.shen_qi_shi)
    ImageView shenQiShi;

    private AlertView userPickerDialog;
    private AlertView companyPickerDialog;
    private FileInputStream is = null;
    List<String> photoInfos = new ArrayList<>();

    @Override
    protected void setRoot() {
        setTitleBar("#FFFFFFFF");
        setContentView(R.layout.activity_certification);
        // 设置启动Activity时不自动弹出软键盘
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }

    @Override
    protected void setup() {
        setStateText();
        setToolBar("认证", "");
        DaggerCertificationComponent.builder().certificationModule(new CertificationModule(this)).build().inject(this);
        presenter.setBiz(biz);

    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        if(!StringUtils.isEmpty(MyApplication.userInfo.getUseable())){
            if(MyApplication.userInfo.getUseable().equals("0")){
                if (StringUtils.isEmpty(MyApplication.userInfo.getRealName())) {
                    certificationInfo.setText("还未实名认证，有疑问请咨询 400-0505-811");
                } else {
                    certificationInfo.setText("实名认证审核中，有疑问请咨询 400-0505-811");
                }
            }else if(MyApplication.userInfo.getUseable().equals("1")){
                certificationInfo.setText("已通过实名认证，有疑问请咨询 400-0505-811");
            }else if(MyApplication.userInfo.getUseable().equals("2")){
                certificationInfo.setText("实名认证审核失败，有疑问请咨询 400-0505-811");
            }else if(MyApplication.userInfo.getUseable().equals("3")){
                certificationInfo.setText("实名认证重新审核中，有疑问请咨询 400-0505-811");
            }
        }
        RxView.clicks(submit)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        presenter.getCheck(userName.getText().toString().trim(), company.getText().toString().trim(),
                                TextUtils.isEmpty(compangyPhone.getText().toString().trim()) ? "" : compangyPhone.getText().toString().trim(), userNumber.getText().toString().trim(), city.getText().toString().trim(), photoInfos);
                    }
                });
        RxView.clicks(userImage)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        showImage();
                    }
                });
        RxView.clicks(companyImage)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        showCompanyImage();
                    }
                });
    }


    @Override
    public void onNetErrorEvent(NetErrorEvent event) {
        super.onNetErrorEvent(event);
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }

    /***
     * Stop location service
     */
    @Override
    protected void onStop() {

        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        biz.onDestory();

    }

    public void showImage() {
        if (userPickerDialog == null) {
            userPickerDialog = AlertUtils.photoPicker(CertificationAct.this, GalleryFinal.copyGlobalFuncationConfig(),
                    new GalleryFinal.OnHanlderResultCallback() {
                        @Override
                        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                            showPhote(resultList.get(0).getPhotoPath(), 0);
                            if(photoInfos.size()>0){
                                photoInfos.set(0, resultList.get(0).getPhotoPath());
                            }else{
                                photoInfos.add(0, resultList.get(0).getPhotoPath());
                            }

                        }

                        @Override
                        public void onHanlderFailure(int requestCode, String errorMsg) {
                            LogUtils.d(requestCode + "", errorMsg);
                        }
                    });
        }
        userPickerDialog.show();
    }

    public void showCompanyImage() {
        if (companyPickerDialog == null) {
            companyPickerDialog = AlertUtils.photoPicker(CertificationAct.this, GalleryFinal.copyGlobalFuncationConfig(),
                    new GalleryFinal.OnHanlderResultCallback() {
                        @Override
                        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                            showPhote(resultList.get(0).getPhotoPath(), 1);
                            if(photoInfos.size()>1){
                                photoInfos.set(1, resultList.get(0).getPhotoPath());
                            }else{
                                photoInfos.add(1, resultList.get(0).getPhotoPath());
                            }
                        }

                        @Override
                        public void onHanlderFailure(int requestCode, String errorMsg) {
                            LogUtils.d(requestCode + "", errorMsg);
                        }
                    });
        }
        companyPickerDialog.show();
    }


    private void showPhote(String path, int type) {
        LogUtils.d(path);
        try {

            is = new FileInputStream(path);

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 4;
            Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);

            // Bitmap bitmap = BitmapFactory.decodeStream(is);
            if (type == 0) {
                userImage.setImageBitmap(bitmap);
                userImage.setScaleType(ImageView.ScaleType.FIT_XY);
            } else if (type == 1) {
                companyImage.setImageBitmap(bitmap);
                companyImage.setScaleType(ImageView.ScaleType.FIT_XY);
            }

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {

            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }



}
